package com.sys.common.utils;

import com.sys.common.enums.BaseEnum;
import lombok.extern.slf4j.Slf4j;

import java.util.Arrays;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author LGY
 * Create by 2025/6/4 9:24
 */
@Slf4j
public class EnumUtil {

    /**
     * 根据code返回对应的枚举类
     *
     * @param code      key值
     * @param enumClass 枚举类
     * @param <E>       key类型
     * @param <T>       枚举类型
     * @return
     */
    public static <E, T extends BaseEnum<E>> T getEnumByCode(final E code, Class<T> enumClass) {
        T target = null;
        try {
            target = Arrays.stream(enumClass.getEnumConstants())
                    .filter(item -> Objects.equals(code, item.getValue()))
                    .collect(Collectors.toList())
                    .get(0);
        } catch (Exception e) {
            log.error("转换枚举异常：", e);
        }
        return target;
    }

    /**
     * 根据name获取对应的枚举类
     *
     * @param name
     * @param enumClass
     * @param <T>
     * @return
     */
    public static <E, T extends BaseEnum<E>> T getEnumByName(final String name, Class<T> enumClass) {
        T target = null;
        try {
            target = Arrays.stream(enumClass.getEnumConstants())
                    .filter(item -> Objects.equals(name, item.getDisplayName()))
                    .collect(Collectors.toList())
                    .get(0);
        } catch (Exception e) {
            log.error("转换枚举异常：", e);
        }
        return target;
    }
}
